package com.pinyoumei.app.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.WebViewActivity;
import com.pinyoumei.app.adapter.PTorderAdapter;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.bean.ToDayPtBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.dialog.BaseDialog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.Map;

import vn.luongvo.widget.iosswitchview.SwitchView;


@SuppressLint("ValidFragment")
public class ToDayPTFragment extends BaseLazyLoadFragment implements View.OnClickListener {
    private String mTitle;
    private Button bt_1;
    private Button bt_2;
    private Button bt_3;
    private SwitchView switchview;//仿IOS滑动选择器
    private LoadingDailog loadingDailog;
    private Gson gson;
    private TextView mTvTotalNum;
    private TextView mTvUserGroupCoupon;
    private TextView mTvSpelledTime;
    private TextView mTvLeftSpellTime;
    private TextView mTvSpelledInTime;
    private TextView mTvSpelledOutTime;
    private ImageView iv_show;
    private PTorderAdapter pTorderAdapter;
    private RecyclerView rv_1;
    private int spell_status = 1;
    private boolean isOpenSwitch = true;

    public static ToDayPTFragment getInstance(String title) {
        ToDayPTFragment sf = new ToDayPTFragment();
        sf.mTitle = title;
        return sf;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_to_day;
    }

    @Override
    public void initView(View rootView) {
        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        gson = new Gson();


        mTvTotalNum = rootView.findViewById(R.id.tv_total_num);
        mTvUserGroupCoupon = rootView.findViewById(R.id.tv_user_group_coupon);
        mTvSpelledTime = rootView.findViewById(R.id.tv_spelled_time);
        mTvLeftSpellTime = rootView.findViewById(R.id.tv_left_spell_time);
        mTvSpelledInTime = rootView.findViewById(R.id.tv_spelled_in_time);
        mTvSpelledOutTime = rootView.findViewById(R.id.tv_spelled_out_time);


        rv_1 = rootView.findViewById(R.id.rv_1);



        LinearLayout ll_1 = rootView.findViewById(R.id.ll_1);
        ll_1.setOnClickListener(this);
        bt_1 = rootView.findViewById(R.id.bt_1);
        bt_1.setOnClickListener(this);
        bt_2 = rootView.findViewById(R.id.bt_2);
        bt_2.setOnClickListener(this);
        bt_3 = rootView.findViewById(R.id.bt_3);
        bt_3.setOnClickListener(this);
        iv_show = rootView.findViewById(R.id.iv_show);
        iv_show.setOnClickListener(this);


        switchview = rootView.findViewById(R.id.switchview);
        switchview.setOnCheckedChangeListener(new SwitchView.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchView switchView, boolean isChecked) {
                if (isChecked) {
                    SwitchviewData(1);
                } else {
                    SwitchviewData(0);
                }
            }
        });

        SmartRefreshLayout mSwipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        mSwipeRefreshLayout.setEnableLoadMore(false);
        mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                InitData();
                refreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();
//        状态 1正在开团 2已团中 3待开团 示例：3
        InitData();
    }

    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("spell_status", spell_status);

        OkGo.<String>post(Constants.TODAY_SPELL_ORDER)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("spell_status", spell_status)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        ToDayPtBean toDayPtBean = gson.fromJson(response.body(), ToDayPtBean.class);
                        if (toDayPtBean.getCode() >= 0) {
//                            是否开启智能连拼 0否 1是
                            if(isOpenSwitch) {
                                switch (toDayPtBean.getResult().getIs_open_continue_spell()) {
                                    case 0:
                                        switchview.setChecked(false);
                                        break;
                                    case 1:
                                        switchview.setChecked(true);
                                        break;

                                    default:
                                        break;
                                }
                                isOpenSwitch = false;
                            }

                            mTvTotalNum.setText("总次数 " + toDayPtBean.getResult().getTotal_num());
                            mTvUserGroupCoupon.setText("开心值 " + toDayPtBean.getResult().getUser_group_coupon());
                            mTvSpelledTime.setText(toDayPtBean.getResult().getSpelled_time() + "");
                            mTvLeftSpellTime.setText(toDayPtBean.getResult().getLeft_spell_time() + "");
                            mTvSpelledInTime.setText(toDayPtBean.getResult().getSpelled_in_time() + "");
                            mTvSpelledOutTime.setText(toDayPtBean.getResult().getSpelled_out_time() + "");

                            rv_1.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
                            pTorderAdapter = new PTorderAdapter(spell_status,R.layout.item_pt_order, toDayPtBean.getResult().getOrder_list());
                            rv_1.setAdapter(pTorderAdapter);
                            View notDataView4 = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) rv_1.getParent(), false);
                            pTorderAdapter.setEmptyView(notDataView4);




                        } else {
                            Toast.makeText(getActivity(), toDayPtBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }


    private void LoadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("spell_status", spell_status);

        OkGo.<String>post(Constants.TODAY_SPELL_ORDER)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("spell_status", spell_status)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        ToDayPtBean toDayPtBean = gson.fromJson(response.body(), ToDayPtBean.class);
                        if (toDayPtBean.getCode() >= 0) {
                            pTorderAdapter.setNewData(toDayPtBean.getResult().getOrder_list());
                            View notDataView4 = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) rv_1.getParent(), false);
                            pTorderAdapter.setEmptyView(notDataView4);
                        } else {
                            Toast.makeText(getActivity(), toDayPtBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }

    private void SwitchviewData(int is_open_continue_spell) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("is_open_continue_spell", is_open_continue_spell);

        OkGo.<String>post(Constants.TODAY_SWITCH)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("is_open_continue_spell", is_open_continue_spell)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.getCode() >= 0) {
                            LoadData();
                            Toast.makeText(getActivity(), baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                        } else {
                            switchview.setChecked(false);
                            Toast.makeText(getActivity(), baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_1:
                //客服
                if (!TextUtils.isEmpty(Constants.KF_URL)) {
                    final Intent intent2 = new Intent(getActivity(), WebViewActivity.class);
                    intent2.putExtra("order_title", "");
                    intent2.putExtra("url", Constants.KF_URL);
                    startActivity(intent2);
                }
                break;
            case R.id.iv_show:
                BaseDialog baseDialog = new BaseDialog(getActivity(), R.layout.dialog_pt_rule);
                baseDialog.show();
                ImageView iv_1 = baseDialog.findViewById(R.id.iv_1);
                iv_1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        baseDialog.dismiss();
                    }
                });
                break;

            case R.id.bt_1:
                spell_status = 1;
                InitData();
                bt_1.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_green_corner_15dp));
                bt_2.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_gray_corner_15dp));
                bt_3.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_gray_corner_15dp));
                bt_1.setTextColor(ContextCompat.getColor(getActivity(), R.color.green_bg));
                bt_2.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_text_color));
                bt_3.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_text_color));

                break;

            case R.id.bt_2:
                spell_status = 2;
                InitData();
                bt_1.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_gray_corner_15dp));
                bt_2.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_green_corner_15dp));
                bt_3.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_gray_corner_15dp));
                bt_1.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_text_color));
                bt_2.setTextColor(ContextCompat.getColor(getActivity(), R.color.green_bg));
                bt_3.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_text_color));

                break;
            case R.id.bt_3:
                spell_status = 3;
                InitData();
                bt_1.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_gray_corner_15dp));
                bt_2.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_gray_corner_15dp));
                bt_3.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.shanpe_green_corner_15dp));
                bt_1.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_text_color));
                bt_2.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_text_color));
                bt_3.setTextColor(ContextCompat.getColor(getActivity(), R.color.green_bg));

                break;
            default:
                break;
        }
    }
}